#!usr/bin/env python  
# -*- coding:utf-8 -*-
"""
@author:'手机视界'
@file: bcm_shortcuts.py
@time: 2018/10/13
utils类，用来封装一些必要的公共方法
"""
import re
from bs4 import BeautifulSoup as bs

from django.forms.models import model_to_dict


def bbd_model_to_dict(instances, fields=None, exclude=None):
    """
    将一个model模型组转化为一个，模型列表并返回
    :param instances: 模型组
    :param fields: 只显示某些字段
    :param exclude: 排除一些字段不予显示
    :return:
    """

    model_list = []
    for instance in instances:
        model_list.append(model_to_dict(instance, fields, exclude))
    return model_list


def translate_zh2en_mark(zh_content: str):
    """
    转换文本中的中文标点为英文标点符号
    :param zh_content: 输入文本
    :return: 英文标点文本
    """
    zh_mark = '！“#￥%&‘’（）*+，-。/：；《=》？@【】…—·{|}~'
    en_mark = '!"#$%&\'\'()*+,-./:;<=>?@[]^_`{|}~'

    en_content = zh_content
    for mark in zh_mark:
        if mark in zh_content:
            # print(mark)
            try:
                en_content = en_content.replace(mark, en_mark[zh_mark.index(mark)])
            except ValueError:
                msg = 'substring not found'
                continue
    return en_content


def prettify_html(content):
    """
    html标签补全
    :param content: 一个html补全的文档
    :return:
    """
    return bs(content, 'lxml').prettify()


def delete_html_tag(html):
    """
    清楚html标签
    :param html:一个html文档
    :return:
    """
    pattern = re.compile(r'<[^>]+>', re.S)
    result = pattern.sub('', html)
    return result
